﻿using SP.Domain.DTO;
using SP.Domain.IRepository;
using SP.Domain.Model;
using SP.Service.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SP.Service
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IRepository<UserTable> _UserTable;
        public UserService(IUserRepository userRepository,
            IRepository<UserTable> UserTable)
        {
            _userRepository = userRepository;
            _UserTable = UserTable;
        }

        public PageModel<UserTable> GetUsers(int pageIndex,int pageSize)
        {
            PageModel<UserTable> pagemodel = new PageModel<UserTable>();
            pagemodel.Total = _UserTable.GetList().Count();
            pagemodel.List = _UserTable.GetList().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return pagemodel;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public UserTable Login(LoginDTO model)
        {
            // return new UserDTO { UserName = input.UserName };
            return _userRepository.Login(model.UserName,model.PassWord);
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddUser(UserTable model)
        {
            model.PassWord = MD5Hash.Hash.GetMD5(model.PassWord);
            var list = _UserTable.GetList().Where(s => s.UserName.Equals(model.UserName)).Count();
            if (list>0)
            {
                return -1;
            }
            return _UserTable.Insert(model);
        }
        //删除用户
        public int DeleteUser(UserTable model)
        {
            return _UserTable.Delete(model);
        }
        //用户修改
        public int UpdateUser(UserTable model)
         {
            return _UserTable.Update(model);
        }
        //用户显示
        public PageModel<UserTable> UserList(int pageIndex, int pageSize, string? UserName)
        {
            var list = _UserTable.GetList().ToList();
            if (!string.IsNullOrEmpty(UserName))
            {
                list = list.Where(s => s.UserName.Contains(UserName)).ToList();
            }
            PageModel<UserTable> pagemodel = new PageModel<UserTable>();
            pagemodel.Total = list.Count();
            pagemodel.List = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return pagemodel;

        }
        //批量删除
        public int BatckUser(string id)
        {
           return _userRepository.BatckUser(id);
        }
        //用户反填
        public UserTable FindUser(int id)
        {
            var list = _UserTable.GetList().Where(s=>s.Id.Equals(id)).FirstOrDefault();
            return list;
        }
    }
}
